/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Coupons;
import pojo.Food;
import pojo.UserCoupon;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author A7med Kotb
 */
public class CouponsJpaController implements Serializable {

    public CouponsJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Coupons coupons) throws RollbackFailureException, Exception {
        if (coupons.getUserCouponCollection() == null) {
            coupons.setUserCouponCollection(new ArrayList<UserCoupon>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Food foodId = coupons.getFoodId();
            if (foodId != null) {
                foodId = em.getReference(foodId.getClass(), foodId.getId());
                coupons.setFoodId(foodId);
            }
            Collection<UserCoupon> attachedUserCouponCollection = new ArrayList<UserCoupon>();
            for (UserCoupon userCouponCollectionUserCouponToAttach : coupons.getUserCouponCollection()) {
                userCouponCollectionUserCouponToAttach = em.getReference(userCouponCollectionUserCouponToAttach.getClass(), userCouponCollectionUserCouponToAttach.getUcId());
                attachedUserCouponCollection.add(userCouponCollectionUserCouponToAttach);
            }
            coupons.setUserCouponCollection(attachedUserCouponCollection);
            em.persist(coupons);
            if (foodId != null) {
                foodId.getCouponsCollection().add(coupons);
                foodId = em.merge(foodId);
            }
            for (UserCoupon userCouponCollectionUserCoupon : coupons.getUserCouponCollection()) {
                Coupons oldCouponIdOfUserCouponCollectionUserCoupon = userCouponCollectionUserCoupon.getCouponId();
                userCouponCollectionUserCoupon.setCouponId(coupons);
                userCouponCollectionUserCoupon = em.merge(userCouponCollectionUserCoupon);
                if (oldCouponIdOfUserCouponCollectionUserCoupon != null) {
                    oldCouponIdOfUserCouponCollectionUserCoupon.getUserCouponCollection().remove(userCouponCollectionUserCoupon);
                    oldCouponIdOfUserCouponCollectionUserCoupon = em.merge(oldCouponIdOfUserCouponCollectionUserCoupon);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Coupons coupons) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Coupons persistentCoupons = em.find(Coupons.class, coupons.getCId());
            Food foodIdOld = persistentCoupons.getFoodId();
            Food foodIdNew = coupons.getFoodId();
            Collection<UserCoupon> userCouponCollectionOld = persistentCoupons.getUserCouponCollection();
            Collection<UserCoupon> userCouponCollectionNew = coupons.getUserCouponCollection();
            if (foodIdNew != null) {
                foodIdNew = em.getReference(foodIdNew.getClass(), foodIdNew.getId());
                coupons.setFoodId(foodIdNew);
            }
            Collection<UserCoupon> attachedUserCouponCollectionNew = new ArrayList<UserCoupon>();
            for (UserCoupon userCouponCollectionNewUserCouponToAttach : userCouponCollectionNew) {
                userCouponCollectionNewUserCouponToAttach = em.getReference(userCouponCollectionNewUserCouponToAttach.getClass(), userCouponCollectionNewUserCouponToAttach.getUcId());
                attachedUserCouponCollectionNew.add(userCouponCollectionNewUserCouponToAttach);
            }
            userCouponCollectionNew = attachedUserCouponCollectionNew;
            coupons.setUserCouponCollection(userCouponCollectionNew);
            coupons = em.merge(coupons);
            if (foodIdOld != null && !foodIdOld.equals(foodIdNew)) {
                foodIdOld.getCouponsCollection().remove(coupons);
                foodIdOld = em.merge(foodIdOld);
            }
            if (foodIdNew != null && !foodIdNew.equals(foodIdOld)) {
                foodIdNew.getCouponsCollection().add(coupons);
                foodIdNew = em.merge(foodIdNew);
            }
            for (UserCoupon userCouponCollectionOldUserCoupon : userCouponCollectionOld) {
                if (!userCouponCollectionNew.contains(userCouponCollectionOldUserCoupon)) {
                    userCouponCollectionOldUserCoupon.setCouponId(null);
                    userCouponCollectionOldUserCoupon = em.merge(userCouponCollectionOldUserCoupon);
                }
            }
            for (UserCoupon userCouponCollectionNewUserCoupon : userCouponCollectionNew) {
                if (!userCouponCollectionOld.contains(userCouponCollectionNewUserCoupon)) {
                    Coupons oldCouponIdOfUserCouponCollectionNewUserCoupon = userCouponCollectionNewUserCoupon.getCouponId();
                    userCouponCollectionNewUserCoupon.setCouponId(coupons);
                    userCouponCollectionNewUserCoupon = em.merge(userCouponCollectionNewUserCoupon);
                    if (oldCouponIdOfUserCouponCollectionNewUserCoupon != null && !oldCouponIdOfUserCouponCollectionNewUserCoupon.equals(coupons)) {
                        oldCouponIdOfUserCouponCollectionNewUserCoupon.getUserCouponCollection().remove(userCouponCollectionNewUserCoupon);
                        oldCouponIdOfUserCouponCollectionNewUserCoupon = em.merge(oldCouponIdOfUserCouponCollectionNewUserCoupon);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = coupons.getCId();
                if (findCoupons(id) == null) {
                    throw new NonexistentEntityException("The coupons with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Coupons coupons;
            try {
                coupons = em.getReference(Coupons.class, id);
                coupons.getCId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The coupons with id " + id + " no longer exists.", enfe);
            }
            Food foodId = coupons.getFoodId();
            if (foodId != null) {
                foodId.getCouponsCollection().remove(coupons);
                foodId = em.merge(foodId);
            }
            Collection<UserCoupon> userCouponCollection = coupons.getUserCouponCollection();
            for (UserCoupon userCouponCollectionUserCoupon : userCouponCollection) {
                userCouponCollectionUserCoupon.setCouponId(null);
                userCouponCollectionUserCoupon = em.merge(userCouponCollectionUserCoupon);
            }
            em.remove(coupons);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Coupons> findCouponsEntities() {
        return findCouponsEntities(true, -1, -1);
    }

    public List<Coupons> findCouponsEntities(int maxResults, int firstResult) {
        return findCouponsEntities(false, maxResults, firstResult);
    }

    private List<Coupons> findCouponsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Coupons.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Coupons findCoupons(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Coupons.class, id);
        } finally {
            em.close();
        }
    }

    public int getCouponsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Coupons> rt = cq.from(Coupons.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
